package org.dwpd.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.dwpd.domain.user.UserDTO;
import org.dwpd.utils.RedisConstants;
import org.dwpd.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * Package:org.dwpd.interceptor
 *
 * @ClassName:RefushTokenInterceptor
 * @Create:2024/8/16 15:36
 **/
@Component
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     *  每次请求前都使用token在redis获取用户信息并存入线程池方便获取
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)){
            //不存在直接放行
            return true;
        }
        //存在
        //基于token获取redis中的用户
        String key = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(key);
        //判断是否存在
        if (entries.isEmpty()){
//            log.info("Refush：用户不存在");
            //不存在，直接放行
            return true;
        }

        //存在，将用户信息存入ThreadLocal
        //先将Hash数据转换为UserDTO对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
//        log.info("用户存在, {}", userDTO);
        UserHolder.saveUser(userDTO);
        //刷新token有效期
        stringRedisTemplate.expire(key,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //放行
        return true;
    }

    /**
     *  每次请求结束后清除线程池中的用户信息，避免溢出
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
